package com.hsmw.api.controller.pub;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hsmw.api.mapper.HsmwUserMapper;
import com.hsmw.api.service.*;
import com.hsmw.api.utils.JSONUtils;
import com.hsmw.api.vo.RelationsInfo;
import com.hsmw.api.vo.WXPushVO;
import com.hsmw.api.vo.WebSocketReturnVO;
import com.hsmw.api.vo.XuniTelNumVO;
import com.htn.common.core.constant.*;
import com.htn.common.core.utils.StringUtils;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.OrderPoolVO;

import java.io.File;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class OrderTimeTaskNew extends TimerTask {

    private HsmwUserDriverService hsmwUserDriverService;

    private HsmwPhoneBindService hsmwPhoneBindService;


    private HsmwUserMapper hsmwUserMapper;

    private HsmwOrderService hsmwOrderService;


    private HsmwVehicleService hsmwVehicleService;

    private WebSocket webSocket;
    private HsmwOrder orderInfo;
    private HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService;
    private RedisCache redisCache;
    public OrderTimeTaskNew(RedisCache redisCache, HsmwOrderDistributeInfoService hsmwOrderDistributeInfoService, HsmwOrder orderInfo, WebSocket webSocket, HsmwUserDriverService hsmwUserDriverService, HsmwUserMapper hsmwUserMapper, HsmwOrderService hsmwOrderService, HsmwVehicleService hsmwVehicleService, HsmwPhoneBindService hsmwPhoneBindService) {
        this.hsmwUserDriverService = hsmwUserDriverService;
        this.hsmwUserMapper = hsmwUserMapper;
        this.hsmwOrderService = hsmwOrderService;
        this.hsmwVehicleService = hsmwVehicleService;
        this.webSocket = webSocket;
        this.orderInfo = orderInfo;
        this.hsmwOrderDistributeInfoService = hsmwOrderDistributeInfoService;
        this.hsmwPhoneBindService=hsmwPhoneBindService;
        this.redisCache = redisCache;
    }

    @Override
    public void run() {
        System.out.println("订单id为" + orderInfo .getId() + "处理执行时间 ==== " + new Date());
        System.out.println("orderPool.get(orderPoolVO.getRequestId())===" +redisCache.getCacheList(orderInfo.getId()).size());
        System.out.println("orderPool.get(orderPoolVO.getRequestId())===" +redisCache.getCacheList(orderInfo.getId()).toString());
        //抢单人员列表
        List<OrderPoolVO> resVos = new ArrayList<>();

        //未选中的 抢单人员列表
        List<OrderPoolVO> unCheckResVos = new ArrayList<>();

        List<OrderPoolVO> data = new ArrayList<>();
        List<JSONObject> result = redisCache.getCacheList(orderInfo.getId());
        if(CollectionUtil.isNotEmpty(result)){
            data= JSONUtils.transferJSONToBean(result);
        }
        resVos = sortByParam(data);
        OrderPoolVO checkedOrderVO = resVos.get(0);
        if(resVos.size()>1){
            for(int i=1;i<resVos.size();i++){
                unCheckResVos.add(resVos.get(i));
            }
        }
        //查询选中的司机信息
        List<HsmwUserDriver> drivers=hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                .eq(HsmwUserDriver::getVehicleId,checkedOrderVO.getVehicleId()));
        String driverUserIds  ="";
        for(HsmwUserDriver driver :drivers){
            driverUserIds= driverUserIds+driver.getUserId()+",";
        }
        if(driverUserIds.endsWith(",")){
            driverUserIds=driverUserIds.substring(0,driverUserIds.length()-1);
        }
        orderInfo.setOrderStatus(OrderStatusEnum.UNRECEIVED.getValue());
        orderInfo.setVehicleId(checkedOrderVO.getVehicleId());
        orderInfo.setUpdateTime(LocalDateTime.now());
       // orderInfo.setDriverIds(driverUserIds);
        hsmwOrderService.updateById(orderInfo);
        //抢单成功以后 将  该订单发布信息置为 已接单
        HsmwOrderDistributeInfo info = new HsmwOrderDistributeInfo();
        info.setDistributeStatus(DistributeStatusEnum.RECEVIED.getValue());
        hsmwOrderDistributeInfoService.update(info, new LambdaQueryWrapper<HsmwOrderDistributeInfo>()
                .eq(HsmwOrderDistributeInfo::getVehicleId, checkedOrderVO.getVehicleId())
                .eq(HsmwOrderDistributeInfo::getOrderId, checkedOrderVO.getOrderId()));

        //司机抢单成功 则 将 司机状态改为 工作中
        HsmwVehicle vehicle = new HsmwVehicle();
        vehicle.setWorkStatus(CommonConstants.VEHICLE_WORK);
        vehicle.setId(checkedOrderVO.getVehicleId());

        if (CollectionUtil.isNotEmpty(drivers)){
            drivers.stream().forEach(hsmwUserDriver -> {
                hsmwUserDriver.setWorkStatus(CommonConstants.DRIVER_WORK);
            });
        }
        hsmwUserDriverService.updateBatchById(drivers);
        //司机抢单成功 则 将 司机状态改为  工作中
        hsmwVehicleService.updateById(vehicle);
        //将订单状态改为

        //通过websocket 长链接推送给客户端抢单成功的信息
        //查询当前车辆下面的所有的司机并给他们推送信息
        List<HsmwUserDriver> driverss=hsmwUserDriverService.list(new LambdaQueryWrapper<HsmwUserDriver>()
                .eq(HsmwUserDriver::getVehicleId,checkedOrderVO.getVehicleId()));
        List<String> userIds =new ArrayList<>();
        if (CollectionUtil.isNotEmpty(driverss)){
            driverss.stream().forEach(driv->{
                userIds.add(driv.getUserId());
            });
            List<HsmwUser> users = hsmwUserMapper.selectBatchIds(userIds);
            if(CollectionUtil.isNotEmpty(users)){
                users.stream().forEach(user -> {
                    WebSocketReturnVO vo = new WebSocketReturnVO();
                    vo.setStatus(WebsocketTypeEnum.GRABBSUCC.getValue());
                    int month = orderInfo.getReachTime().getMonth().getValue();
                    int day = orderInfo.getReachTime().getDayOfMonth();
                    int hour = orderInfo.getReachTime().getHour();
                    int minute = orderInfo.getReachTime().getMinute();
                    String minutes ="";
                    if(0==minute){
                        minutes = "00";
                    }
                    String retMsg = "请于" + month + "月" + day + "日 " + hour + ":" + minutes + "之前到达指定地点";
                    vo.setMessage(retMsg);
                    String returnJson = JSONObject.toJSON(vo).toString();
                    System.out.println("returnJson" + returnJson);
                    //通过手机号进行长链接推送抢单成功的信息。
                    webSocket.AppointSending(user.getUsername(), returnJson);
                    TencentPushUtils.pushMsg("恭喜您,抢单成功！", user.getUsername(),"order_status_2");
                });
            }
        }

        //抢完单以后 ，将该抢单信息从redis 中 删除掉
        redisCache.deleteObject(orderInfo.getId());
        String vehiclePaltes = checkedOrderVO.getVehicleNum();
        HsmwOrder order = hsmwOrderService.getById(orderInfo.getId());
        //推送 工长信息变化
        HsmwUser formanUser = hsmwUserMapper.selectById(orderInfo.getCreateUser());
        WXPushVO vo = new WXPushVO();
        vo.setMainTitle(PushOrderStatusEnum.UNRECEIVED.getName());
        vo.setOrderId(orderInfo.getId());
        vo.setConstructionAddress(order.getItemPositionDetail());
        vo.setVehicleNums(vehiclePaltes);
        vo.setArriveTime(order.getReachTime());
        vo.setOpenId(formanUser.getOpenId());
        vo.setTemplateId(CommonConstants.WX_FOREMEN_TEMP_ID);
        WeapPushUtils.pushForemanMsg(vo,null);

        //未接到订单的人如果不为空 则推送抢单失败的信息
        if (CollectionUtil.isNotEmpty(unCheckResVos)) {
            for (OrderPoolVO poolVO : unCheckResVos) {
                //通过手机号进行长链接推送抢单成功的信息。
                WebSocketReturnVO vo1 = new WebSocketReturnVO();
                vo1.setStatus(WebsocketTypeEnum.GRABBFAIL.getValue());
                vo1.setMessage("抢单失败");
                String returnJson = JSONObject.toJSON(vo1).toString();
                webSocket.AppointSending(poolVO.getDriverUsername(), returnJson);
                //抢单失败的推送
                System.out.println("抢单失败的推送信息---returnJson=="+returnJson);
                TencentPushUtils.pushMsg("很遗憾，抢单失败！", poolVO.getDriverUsername(),"has_new_message");
            }
        }
    }


    public static List<OrderPoolVO> sortByParam(List<OrderPoolVO> vos) {
        //如果选择的是
        Collections.sort(vos, new Comparator<OrderPoolVO>() {
            @Override
            public int compare(OrderPoolVO v1, OrderPoolVO v2) {
                if (v2.getScore() != v1.getScore()) {
                    return Integer.parseInt(v2.getScore()) - Integer.parseInt(v1.getScore());
                } else {
                    return v2.getGrabTime().compareTo(v1.getGrabTime());
                }
            }
        });
        return vos;
    }

    public static void main(String[] args) {

        List<OrderPoolVO> vos = new ArrayList<>();
        OrderPoolVO vo1 = new OrderPoolVO();
        vo1.setScore("500");
        vos.add(vo1);
        OrderPoolVO vo2 = new OrderPoolVO();
        vo2.setScore("501");
        vos.add(vo2);
        Collections.sort(vos, new Comparator<OrderPoolVO>() {
            @Override
            public int compare(OrderPoolVO v1, OrderPoolVO v2) {
                if (v2.getScore() != v1.getScore()) {
                    return Integer.parseInt(v2.getScore()) - Integer.parseInt(v1.getScore());
                } else {
                    return v2.getGrabTime().compareTo(v1.getGrabTime());
                }
            }
        });

        System.out.println(vos.get(0));

    }

}